package blue.web.dao.service;

import blue.commons.enums.SettingTypeEnum;
import blue.commons.enums.StatusEnum;
import blue.commons.enums.TagEnum;
import blue.commons.models.TitleValue;
import blue.dao.base.BaseMapper;
import blue.erp.model.BlueCourse;
import blue.erp.model.SysUser;
import blue.tools.commons.BlueStringUtils;
import blue.tools.constants.BlueContants;
import blue.web.commons.service.TreeService;
import blue.workevaluate.dao.WorkTaskStudentQuestionMapper;
import blue.workevaluate.model.*;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
@Lazy
@Service
public class WorkStudentQuestionService extends BaseService {

    @Autowired
    private WorkTaskStudentQuestionMapper workTaskStudentQuestionMapper;
    @Lazy
    @Autowired
    private WorkTaskService workTaskService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private BlueCourseService blueCourseService;

    @Autowired
    private TreeService treeService;

    @Autowired
    private WorkSettingService workSettingService;
    @Lazy
    @Autowired
    private WorkTaskStudentSummerService workTaskStudentSummerService;

    private final String prefix_question_user_tagedcount="question_user_tagedcount";

    private final String prefix_question_user_distinctInfo="question_user_distinctInfo";

    public int deleteBatch(String ids, SysUser sysUser) {
        List idList= BlueStringUtils.convertString2Num(ids,",");
        WorkTaskStudentQuestionExample example=new WorkTaskStudentQuestionExample();
        example.createCriteria().andIdIn(idList);

        return this.getBaseMapper().deleteByExample(example);
    }

    public int batchSave(WorkTaskStudentQuestion record){
       if(record==null || record.getTaskId()==null || record.getSchoolid()==null){
           return 0;
       }

       WorkTask workTask=workTaskService.selectById(record.getTaskId(),record.getSchoolid());
       if(workTask==null || StringUtils.isBlank(workTask.getData())){
           return 0;
       }

       //超期
       if(workTask.getEndtime()!=null && workTask.getEndtime().before(new Date())) {
           return 0;
       }

       List<TitleValue> titleValueList=treeService.getLeafNodes(workTask.getData());
       int result=0;
       for(TitleValue titleValue:titleValueList){
           WorkTaskStudentQuestion workTaskStudentQuestion=new WorkTaskStudentQuestion();
           workTaskStudentQuestion.setSchoolid(record.getSchoolid());
           workTaskStudentQuestion.setTaskId(record.getTaskId());
           workTaskStudentQuestion.setQuestionId(titleValue.getValue());
           workTaskStudentQuestion.setUserId(record.getUserId());
           workTaskStudentQuestion.setTagresult(record.getTagresult());
           result+=this.save(workTaskStudentQuestion);
       }

       return result;
    }

    public int save(WorkTaskStudentQuestion record) {
        if(record==null){
            return 0;
        }

        if(record.getId()!=null){
            WorkTaskStudentQuestionExample example=new WorkTaskStudentQuestionExample();
            WorkTaskStudentQuestionExample.Criteria criteria=example.createCriteria().andSchoolidEqualTo(record.getSchoolid()).andIdEqualTo(record.getId());

            WorkTaskStudentQuestion oldRecord= (WorkTaskStudentQuestion) this.selectByPrimaryKey(record.getId(),record.getSchoolid());
            clearCache(record.getSchoolid(),oldRecord.getTaskId(),oldRecord.getUserId());

            return this.baseSave(record,example);
        }

        if(record.getTaskId()==null || record.getTaskId()<0){
           return 0;
        }

        WorkTask workTask=workTaskService.selectById(record.getTaskId(),record.getSchoolid());

        if(workTask==null){
            return 0;
        }

        //超期
        if(workTask.getEndtime()!=null && workTask.getEndtime().before(new Date())) {
            return 0;
        }

        record.setGradeLevel(workTask.getGradeLevel());
        if(workTask.getCourseid()!=null && workTask.getCourseid()>0){
            BlueCourse blueCourse=blueCourseService.selectByPrimaryKey(workTask.getCourseid(),record.getSchoolid(),false);
            if(blueCourse!=null){
                record.setCourseName(blueCourse.getName());
            }
        }
        //处理班级
        if(record.getUserId()!=null) {
            SysUser userInfo = (SysUser) sysUserService.selectByPrimaryKey(record.getUserId(), record.getSchoolid());
            List userClassIds=BlueStringUtils.convertString2Num(userInfo.getClassIds(),",");
            userClassIds.addAll(BlueStringUtils.convertString2Num(userInfo.getGroupIds(),","));
            List<Long> classIds=BlueStringUtils.getIntersection(StringUtils.join(userClassIds,","),workTask.getClassIds());
            if(CollectionUtils.isEmpty(classIds) || classIds.size()>1){
                return 0;
            }
            record.setClassId(classIds.get(0));
        }


            WorkTaskStudentQuestionExample example=new WorkTaskStudentQuestionExample();
        WorkTaskStudentQuestionExample.Criteria criteria=example.createCriteria().andSchoolidEqualTo(record.getSchoolid())
                .andTaskIdEqualTo(record.getTaskId()).andQuestionIdEqualTo(record.getQuestionId()).andUserIdEqualTo(record.getUserId());

        clearCache(record.getSchoolid(),record.getTaskId(),record.getUserId());
        return this.baseSave(record,example);
    }

    //用于扫表，将没有添加属性表数据批量添加上属性，比如问题的知识点 类型等属性
    @Async
    public void scanAddAttributes(int pageSize){
        PageHelper.startPage(1,pageSize);
        WorkTaskStudentQuestionExample example=new WorkTaskStudentQuestionExample();
        WorkTaskStudentQuestionExample.Criteria criteria=example.createCriteria().andStatusNotEqualTo((byte) StatusEnum.Handled.getValue());
        List<WorkTaskStudentQuestion>  workTaskStudentQuestionList=this.select(example);
        if(CollectionUtils.isNotEmpty(workTaskStudentQuestionList)){
            for(WorkTaskStudentQuestion workTaskStudentQuestion:workTaskStudentQuestionList){
                //将问题的类别数据持久化到db中，方便学生多样化查询自己的错题
                TitleValue titleValue=workTaskService.queryNodeByKey(workTaskStudentQuestion.getTaskId(),workTaskStudentQuestion.getQuestionId(),workTaskStudentQuestion.getSchoolid());
                if(titleValue!=null && StringUtils.isNotBlank(titleValue.getExtend())){
                    QuestionAttributes attributes= JSONObject.parseObject(titleValue.getExtend(),QuestionAttributes.class);
                    attributes.wrap2StudentQuestion(workTaskStudentQuestion);
                }

                //将课程和年级信息持久化
                WorkTask workTask=workTaskService.selectById(workTaskStudentQuestion.getId(),workTaskStudentQuestion.getSchoolid());
                if(workTask!=null){
                    workTaskStudentQuestion.setCourseName(workTask.getCoursename());
                    workTaskStudentQuestion.setGradeLevel(workTask.getGradeName());
                }

                workTaskStudentQuestion.setStatus((byte) StatusEnum.Handled.getValue());
                this.save(workTaskStudentQuestion);
            }
        }else {
            redisService.setValue(BlueContants.prefix_timertask_studentquestion,"nodata",BlueContants.hour);
        }
    }

    //获取学生对任务的标记个数
    public Integer getTaskTagCount(Long taskId,Long schoolId,Long userId){
        if(taskId==null || schoolId==null || userId==null){
            return 0;
        }

        Object tagedCount=redisService.getValue(String.format("%s_%s_%s_%s",prefix_question_user_tagedcount,schoolId,taskId,userId));
        if(tagedCount!=null){
            return JSONObject.parseObject(tagedCount.toString(),Integer.class);
        }
        WorkTaskStudentQuestionExample example=new WorkTaskStudentQuestionExample();
        WorkTaskStudentQuestionExample.Criteria criteria=example.createCriteria().andSchoolidEqualTo(schoolId).andTaskIdEqualTo(taskId).andUserIdEqualTo(userId);
        List result=this.select(example);
        if(CollectionUtils.isEmpty(result)){
            tagedCount=0;
        }else {
            tagedCount=result.size();
        }

        redisService.setValue(String.format("%s_%s_%s_%s",prefix_question_user_tagedcount,schoolId,taskId,userId),tagedCount+"");

        return (Integer) tagedCount;

    }


    public List<WorkTaskStudentQuestion> selectByObject(WorkTaskStudentQuestion record,boolean onlyCurrentUser,boolean showName){

        WorkTaskStudentQuestionExample example=new WorkTaskStudentQuestionExample();
        WorkTaskStudentQuestionExample.Criteria criteria=example.createCriteria().andSchoolidEqualTo(record.getSchoolid());

        if(record.getId()!=null){
            criteria.andIdEqualTo(record.getId());
        }else {

            if(onlyCurrentUser){
                criteria.andUserIdEqualTo(record.getUserId());
            }

            if(StringUtils.isNotBlank(record.getQuestionId())){
                criteria.andQuestionIdEqualTo(record.getQuestionId());
            }

            if(record.getTagresult()!=null && record.getTagresult()>0){
                criteria.andTagresultEqualTo(record.getTagresult());
            }

            if(StringUtils.isNotBlank(record.getCourseName()) && !BlueContants.tag_all.equalsIgnoreCase(record.getCourseName())){
                criteria.andCourseNameEqualTo(record.getCourseName());
            }

            if(StringUtils.isNotBlank(record.getGradeLevel())){
                criteria.andGradeLevelEqualTo(record.getGradeLevel());
            }

            if(record.getTaskId()!=null && record.getTaskId()>0){
                criteria.andTaskIdEqualTo(record.getTaskId());
            }
            if(record.getClassId()!=null && record.getClassId()>0){
                criteria.andClassIdEqualTo(record.getClassId());
            }
        }
        List<WorkTaskStudentQuestion>  workTaskStudentQuestionList=this.select(example);

        //封装name
        if(showName && CollectionUtils.isNotEmpty(workTaskStudentQuestionList)){
            for(WorkTaskStudentQuestion workTaskStudentQuestion:workTaskStudentQuestionList){
                WorkTask workTask=workTaskService.selectById(workTaskStudentQuestion.getTaskId(),record.getSchoolid());
                if(workTask==null || StringUtils.isBlank(workTask.getData())){
                    continue;
                }
                workTaskStudentQuestion.setAttachmenturls(workTask.getAttachmenturls());

                WorkTaskStudentSummer workTaskStudentSummer=workTaskStudentSummerService.selectUserTask(workTask.getId(),workTaskStudentQuestion.getUserId(),record.getSchoolid());
                if(workTaskStudentSummer!=null){
                    workTaskStudentQuestion.setStudentAttachmenturls(workTaskStudentSummer.getAttachmenturls());
                }

                TitleValue titleValue=treeService.getNodeByKey(workTaskStudentQuestion.getQuestionId(),workTask.getData());
                if(titleValue==null){
                    continue;
                }
                workTaskStudentQuestion.setTaskName(workTask.getName());
                workTaskStudentQuestion.setName(titleValue.getTitle());
                workTaskStudentQuestion.setQuestionIndex(titleValue.getIndex());

                HashMap settingMap = workSettingService.selectByTaskId(workTask.getId(),record.getSchoolid());

                WorkSetting knowledgeSetting=settingMap.get(SettingTypeEnum.knowledge.getValue())==null?null:JSONObject.parseObject(settingMap.get(SettingTypeEnum.knowledge.getValue()).toString(),WorkSetting.class);
                WorkSetting capabilitySetting=settingMap.get(SettingTypeEnum.capability.getValue())==null?null:JSONObject.parseObject(settingMap.get(SettingTypeEnum.capability.getValue()).toString(),WorkSetting.class);

                if(knowledgeSetting!=null){
                    workTaskStudentQuestion.setKnowledgeList(treeService.getNodeListByKeys(workTaskStudentQuestion.getKnowledges(),knowledgeSetting.getData()));
                }

                if(capabilitySetting!=null){
                    workTaskStudentQuestion.setCapabilitieList(treeService.getNodeListByKeys(workTaskStudentQuestion.getCapabilities(),capabilitySetting.getData()));
                }
            }
        }

        return workTaskStudentQuestionList;
    }

    public WorkTaskStudentQuestion selectById(Long id,Long schoolId){

        if(id==null || schoolId==null){
            return null;
        }

        Object result=this.selectByPrimaryKey(id,schoolId);
        if(result==null){
            return null;
        }

        return (WorkTaskStudentQuestion) result;

    }


    public List<String> selectDistinct(WorkTaskStudentQuestion record,boolean isFromDb){

        if(record==null || record.getUserId()==null){
            return null;
        }

        if(!isFromDb){
            Object cacheObject=redisService.getValue(String.format("%s_%s_%s_%s",prefix_question_user_distinctInfo,record.getSchoolid(),record.getUserId(),record.getTypeid()));
            if(cacheObject!=null){
                return JSONArray.parseArray(cacheObject.toString(),String.class);
            }
        }


        WorkTaskStudentQuestionExample example=new WorkTaskStudentQuestionExample();
        WorkTaskStudentQuestionExample.Criteria criteria=example.createCriteria().andSchoolidEqualTo(record.getSchoolid()).andUserIdEqualTo(record.getUserId()).andTagresultEqualTo(TagEnum.Wrong.getKey());

        List result=null;

        if("course".equalsIgnoreCase(record.getTypeid())){
            result= workTaskStudentQuestionMapper.selectDistinctCourse(example);
        }else if ("grade".equalsIgnoreCase(record.getTypeid())){
            result= workTaskStudentQuestionMapper.selectDistinctGrade(example);
        }

        if(!isFromDb && CollectionUtils.isNotEmpty(result)){
            redisService.setValue(String.format("%s_%s_%s_%s",prefix_question_user_distinctInfo,record.getSchoolid(),record.getUserId(),record.getTypeid()),JSONArray.toJSONString(result));
        }

        return result;
    }

    @Override
    public BaseMapper getBaseMapper() {
        return this.workTaskStudentQuestionMapper;
    }

    @Override
    public void clearCache(Long schoolId,Object... extend) {
        redisService.vagueDelete(String.format("%s_%s_%s_%s",prefix_question_user_tagedcount,schoolId,extend[0],extend[1]));
        redisService.vagueDelete(BlueContants.prefix_timertask_studentquestion);
    }

}
